package com.syni.mdd.sjb.common.datatreaure.service.impl.databank.saasminapp;

import com.alibaba.fastjson.JSON;
import com.sun.corba.se.spi.ior.ObjectKey;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.config.StoreIdVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.coupon.IdRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.goods.*;
import com.syni.mdd.sjb.common.datatreaure.service.databank.saasminapp.GoodsService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

@Service
@Log4j2
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private UserRestService userRestService;

    @Override
    public Map<String, Object> categoryAndGoodsList(GoodListRqVo goodListRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "notAuth/categoryAndGoodsList/list";
            Map<String, Object> params = BeanUtils.objectToMap(goodListRqVo);
            Map<String, Object> resultMap = reqMember(postUrl, goodListRqVo.getToken(), goodListRqVo.getUserId(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> sellOutProduct(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/sellout/" + sellOutRqVo.getId();
            Map<String, Object> resultMap = postReqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> recoverProduct(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/toSell/" + sellOutRqVo.getId();
            Map<String, Object> resultMap = postReqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> goodsPutOff(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/putoff?id=" + sellOutRqVo.getId();
            Map<String, Object> resultMap = postReqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> goodsPutOn(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/puton?id=" + sellOutRqVo.getId();
            Map<String, Object> resultMap = postReqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> goodsDetail(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "notAuth/product?id=" + sellOutRqVo.getId();
            Map<String, Object> resultMap = reqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(), new HashMap<>());
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> goodsDelete(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/delete/" + sellOutRqVo.getId();
            Map<String, Object> resultMap = reqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(), new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> goodsSaveOrUpdate(SaveOrUpdateRqVo saveOrUpdateRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/saveOrUpdate";
            Map<String, Object> params = BeanUtils.objectToMap(saveOrUpdateRqVo);
            Map<String, Object> resultMap = postReqMember(postUrl, saveOrUpdateRqVo.getToken(), saveOrUpdateRqVo.getUserId(), false,new HashMap<>(),params);
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> updateSkuStock(UpdateSkuStockRqVo updateSkuStockRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsSkuStock/update";
            Map<String, Object> params = BeanUtils.objectToMap(updateSkuStockRqVo);
            Map<String, Object> resultMap = postReqMember(postUrl, updateSkuStockRqVo.getToken(), updateSkuStockRqVo.getUserId(), false,new HashMap<>(),params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> deleteSkuStock(SellOutRqVo sellOutRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsSkuStock/delete/" +sellOutRqVo.getId();
            Map<String, Object> resultMap = reqMember(postUrl, sellOutRqVo.getToken(), sellOutRqVo.getUserId(),new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getStoreTaste(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/external/list";
            Map<String,Object> headMap = new HashMap<>();
            headMap.put("storeId",storeIdVo.getStoreId());
            Map<String, Object> resultMap = postReqMember(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(),true,headMap,new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> delExtraAttribute(IdRqVo idRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/external/delete/" + idRqVo.getId();
            Map<String,Object> headMap = new HashMap<>();
            headMap.put("storeId",idRqVo.getStoreId());
            Map<String, Object> resultMap = postReqMember(postUrl, idRqVo.getToken(), idRqVo.getUserId(),true,headMap,new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> addProductAttribute(AddProductAttributeRqVo addProductAttributeRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProduct/external/add";
            Map<String,Object> headMap = new HashMap<>();
            headMap.put("storeId",addProductAttributeRqVo.getStoreId());
            Map<String, Object> params = BeanUtils.objectToMap(addProductAttributeRqVo);
            Map<String, Object> resultMap = postReqMember(postUrl, addProductAttributeRqVo.getToken(), addProductAttributeRqVo.getUserId(),true,headMap,params);
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> updateSort(UpdateSortRqVo updateSortRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/updateSort?id=" + updateSortRqVo.getId() + "&target=" + updateSortRqVo.getTarget();
            Map<String, Object> resultMap = postReqMember(postUrl, updateSortRqVo.getToken(), updateSortRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> batchUpdateSort(BatchUpdateSortRqVo batchUpdateSortRqVo) {
        try{
            String url = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/batchUpdateSort";
            String token = RequestHeaderData.getRequestHeaderData().getString("token");
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(batchUpdateSortRqVo.getUserId(),token);
            if(!rpcResponseVo.isSuccess()){
                return ResultMapHelper.failure(rpcResponseVo.getMsg());
            }
            String minitoken = rpcResponseVo.getData().toString();
            String requestBody = RestTemplateUtils.postForEntityForJsonByLoadBalanced(url,new HashSet<>(batchUpdateSortRqVo.getBatchList()),RestTemplateUtils.getSassHeader(minitoken));
            Map<String,Object> resultMap = JSON.parseObject(requestBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }


    @Override
    public Map<String, Object> getClassifyList(ClassifyListRqVo classifyListRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/list";
            Map<String,Object> params = BeanUtils.objectToMap(classifyListRqVo);
            Map<String, Object> resultMap = reqMember(postUrl, classifyListRqVo.getToken(), classifyListRqVo.getUserId(), params);
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> editClassify(EditClassifyRqVo editClassifyRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/update/"+editClassifyRqVo.getId();
            Map<String, Object> params = BeanUtils.objectToMap(editClassifyRqVo);
            Map<String, Object> resultMap = postReqMember(postUrl, editClassifyRqVo.getToken(), editClassifyRqVo.getUserId(), false,new HashMap<>(),params);
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> createClassify(CreateClassifyRqVo createClassifyRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/create";
            Map<String, Object> params = BeanUtils.objectToMap(createClassifyRqVo);
            Map<String, Object> resultMap = postReqMember(postUrl, createClassifyRqVo.getToken(), createClassifyRqVo.getUserId(), false,new HashMap<>(),params);
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> deleteClassify(DeleteClassifyRqVo deleteClassifyRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/delete/" + deleteClassifyRqVo.getId();
            Map<String, Object> resultMap = postReqMember(postUrl, deleteClassifyRqVo.getToken(), deleteClassifyRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getClassifyGoodList(DeleteClassifyRqVo deleteClassifyRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/get/" + deleteClassifyRqVo.getId();
            Map<String, Object> resultMap = postReqMember(postUrl, deleteClassifyRqVo.getToken(), deleteClassifyRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> removeProduct(RemoveProductRqVo removeProductRqVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.goods.service") + "pms/PmsProductCategory/removeProduct?id=" + removeProductRqVo.getId() + "&productId=" + removeProductRqVo.getProductId();
            Map<String, Object> resultMap = postReqMember(postUrl, removeProductRqVo.getToken(), removeProductRqVo.getUserId(), false,new HashMap<>(),new HashMap<>());
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }



    public Map<String,Object> reqMember(String requestUrl,String token,Integer userId,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                String reponseBody = RestTemplateUtils.getForEntityWithHead(requestUrl,params,RestTemplateUtils.getSassHeader(minitoken));
                resultMap = JSON.parseObject(reponseBody,Map.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }

    public Map<String,Object> postReqMember(String requestUrl,String token,Integer userId,
                                Boolean isExtra,Map<String,Object> extraMap,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                Map<String, Object> saasHeader = RestTemplateUtils.getSassHeader(minitoken);
                if(isExtra){
                    saasHeader.putAll(extraMap);
                }
                String reponseBody = RestTemplateUtils.postForEntityForJsonByLoadBalanced(requestUrl,params,saasHeader);
                resultMap = JSON.parseObject(reponseBody,Map.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }

    public Map<String,Object> postFormReqMember(String requestUrl,String token,Integer userId,
                                Boolean isExtra,Map<String,Object> extraMap,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                Map<String, Object> saasHeader = RestTemplateUtils.getSassHeader(minitoken);
                if(isExtra){
                    saasHeader.putAll(extraMap);
                }
                String reponseBody = RestTemplateUtils.postForEntity(RestTemplateUtils.getLoadRestTemplate(),requestUrl,params,saasHeader);
                resultMap = JSON.parseObject(reponseBody,Map.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }
}
